package bruce.listener;

import cn.hutool.json.JSONUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

/**
 * @author Bruce
 */
public class MyInterceptor1  implements HandlerInterceptor {

	private Logger log = LoggerFactory.getLogger(this.getClass());
	private String unknownKey = "unknown";
	@Override
	public void afterCompletion(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, Exception arg3)
			throws Exception {

	}

	@Override
	public void postHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2, ModelAndView arg3)
			throws Exception {
		// TODO Auto-generated method stub

	}

	@Override
	public boolean preHandle(HttpServletRequest arg0, HttpServletResponse arg1, Object arg2) throws Exception {
		arg1.setHeader("Access-Control-Allow-Origin", "*");
		arg1.setHeader("Access-Control-Allow-Methods", "POST, GET, OPTIONS, DELETE");
		arg1.setHeader("Access-Control-Max-Age", "3600");
		arg1.setHeader("Access-Control-Allow-Headers", "-requested-with");
		arg1.setCharacterEncoding("UTF-8");
		log.info("ip: {} , url: {}",getIp(arg0),arg0.getRequestURI());
		log.info("queryString: {} ",arg0.getQueryString());
		log.info("parameterMap: {} ",JSONUtil.parseFromMap(arg0.getParameterMap()));
		return true;
	}

	/**
	 * 获取ip
	 * @param request
	 * @return
	 */
	public  String getIp(HttpServletRequest request) {
		String ip = request.getHeader("x-forwarded-for");
		if (ip == null || ip.length() == 0 || unknownKey.equalsIgnoreCase(ip)) {
			ip = request.getHeader("Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || unknownKey.equalsIgnoreCase(ip)) {
			ip = request.getHeader("WL-Proxy-Client-IP");
		}
		if (ip == null || ip.length() == 0 || unknownKey.equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_CLIENT_IP");
		}
		if (ip == null || ip.length() == 0 || unknownKey.equalsIgnoreCase(ip)) {
			ip = request.getHeader("HTTP_X_FORWARDED_FOR");
		}
		if (ip == null || ip.length() == 0 || unknownKey.equalsIgnoreCase(ip)) {
			ip = request.getRemoteAddr();
		}
		return ip;
	}
}
